<template>
  <yd-input
    @input="handleInput"
    ref="input"
    :required="required"
    :regex="reg"
    :placeholder="placeholder"
    :disabled="disabled"
    :show-clear-icon="showClearIcon"
    :value="value"
    :show-error-icon="showIcon && !disabled"
    :show-success-icon="showIcon && !disabled"
    :show-required-icon="showIcon && !disabled"
    :type="type"
    :readonly="readonly"></yd-input>
</template>
<script>
  export default {
    name: 'xf-input',
    props: {
      placeholder: {type: String},
      valid: {type: null},
      value: {type: null, default: ''},
      showClearIcon: {type: Boolean, default: true},
      readonly: {type: Boolean, default: false},
      disabled: {type: Boolean, default: false},
      showIcon: {type: Boolean, default: true},
      type: {type: String, default: 'text'}
    },
    data() {
      return {
        required: false,
        requiredMsg: '',
        reg: String(/.*/),
        regMsg: ''
      }
    },
    methods: {
      handleInput(val) {
        this.$emit('input', val)
      },
      validValue() {
        if (this.$refs.input.valid) {
          return true
        } else if (this.$refs.input.errorCode === 'NOT_NULL') {
          this.$message.toast(this.requiredMsg)
          return new Error(this.requiredMsg)
        } else {
          this.$message.toast(this.regMsg)
          return new Error(this.regMsg)
        }
      },
      handleValid(valid) {
        if (valid && !this.disabled) {
          valid.forEach(item => {
            if (item.hasOwnProperty('required') && item.required) {
              this.required = true
              this.requiredMsg = item.msg || ''
            }
            if (item.hasOwnProperty('reg')) {
              this.reg = String(item.reg)
              this.regMsg = item.msg || ''
            }
          })
        }
      }
    },
    created() {
      this.handleValid(this.valid)
      this.$watch('valid', this.handleValid)
    }
  }
</script>
